package com.knowledgeqa.system.controller;

import com.knowledgeqa.system.common.Result;
import com.knowledgeqa.system.common.ResultCode;
import com.knowledgeqa.system.entity.User;
import com.knowledgeqa.system.entity.Question;
import com.knowledgeqa.system.entity.Answer;
import com.knowledgeqa.system.entity.CoinTransaction;
import com.knowledgeqa.system.mapper.UserMapper;
import com.knowledgeqa.system.service.UserService;
import com.knowledgeqa.system.service.QuestionService;
import com.knowledgeqa.system.service.AnswerService;
import com.knowledgeqa.system.service.CoinTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private CoinTransactionService coinTransactionService;
    
    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result adminLogin(@RequestBody Map<String, String> loginInfo) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            return new Result<>(ResultCode.PARAM_ERROR.getCode(), "用户名和密码不能为空", null);
        }
        
        // 使用login方法验证用户身份，该方法会正确处理密码验证
        User user = userService.login(username, password);
        if (user == null || user.getRole() != 1) {
            return new Result<>(ResultCode.AUTHENTICATION_FAILED.getCode(), "管理员账号或密码错误", null);
        }
        
        // 登录成功，返回管理员信息
        Map<String, Object> data = new HashMap<>();
        data.put("adminId", user.getId());
        data.put("adminUsername", user.getUsername());
        data.put("role", user.getRole());
        
        return new Result<>(ResultCode.SUCCESS.getCode(), "登录成功", data);
    }

    /**
     * 获取系统统计数据
     */
    @GetMapping("/stats/users")
    public Result getTotalUsers() {
        // 获取用户总数
        List<User> users = userService.findAll();
        Map<String, Object> data = new HashMap<>();
        data.put("count", users != null ? users.size() : 0);
        return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
    }

    @GetMapping("/stats/questions")
    public Result getTotalQuestions() {
        // 获取问题总数
        Map<String, Object> params = new HashMap<>();
        int count = questionService.findCount(params);
        Map<String, Object> data = new HashMap<>();
        data.put("count", count);
        return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
    }

    /**
     * 获取悬赏金额最高的前三个问题
     */
    @GetMapping("/questions/rewarded-top3")
    public Result<List<Map<String, Object>>> getTop3RewardedQuestions() {
        List<Question> questions = questionService.findTop3RewardedQuestions();
        
        // 构建前端需要的问题信息列表
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("reward", question.getRewardAmount());
            questionInfo.put("coinReward", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            
            // 获取提问者用户名
            try {
                String username = userService.getUsernameById(question.getUserId());
                questionInfo.put("username", username);
            } catch (Exception e) {
                questionInfo.put("username", "未知用户");
            }
            
            questionList.add(questionInfo);
        }
        
        return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", questionList);
    }

    @GetMapping("/stats/answers")
    public Result getTotalAnswers() {
        // 获取回答总数
        List<Answer> answers = answerService.findAll();
        int count = answers.size();
        Map<String, Object> data = new HashMap<>();
        data.put("count", count);
        return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
    }

    @GetMapping("/stats/coins")
    public Result getTotalCoins() {
        // 由于UserService中可能没有countTotalCoins方法，返回模拟数据
        Map<String, Object> data = new HashMap<>();
        data.put("count", 5000); // 模拟数据
        return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/users")
    public Result getUserList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword) {
        
        // 使用findAll获取所有用户，然后在内存中进行分页和过滤
        List<User> allUsers = userService.findAll();
        List<User> filteredUsers = allUsers;
        
        // 根据关键词过滤
        if (keyword != null && !keyword.isEmpty()) {
            filteredUsers = allUsers.stream()
                    .filter(user -> 
                        (user.getUsername() != null && user.getUsername().contains(keyword)) ||
                        (user.getNickname() != null && user.getNickname().contains(keyword)) ||
                        (user.getEmail() != null && user.getEmail().contains(keyword))
                    )
                    .collect(java.util.stream.Collectors.toList());
        }
        
        // 分页处理
        int total = filteredUsers.size();
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        List<User> paginatedUsers = start < end ? filteredUsers.subList(start, end) : new java.util.ArrayList<>();
        
        Map<String, Object> data = new HashMap<>();
        data.put("users", paginatedUsers);
        data.put("total", total);
        data.put("page", page);
        data.put("pageSize", pageSize);
        
        return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
    }
    
    /**
     * 获取单个用户信息
     */
    @GetMapping("/users/{userId}")
    public Result getUserById(@PathVariable Long userId) {
        try {
            System.out.println("获取用户信息，用户ID: " + userId);
            // 检查用户是否存在
            User user = userService.findById(userId);
            System.out.println("查询到的用户信息: " + user);
            if (user == null) {
                System.out.println("用户不存在，用户ID: " + userId);
                return Result.error(ResultCode.NOT_FOUND, "用户不存在");
            }
            
            // 返回用户信息（密码已经在service层处理为null）
            return Result.success("获取用户信息成功", user);
        } catch (Exception e) {
            System.err.println("获取用户信息过程中发生异常: ");
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 禁言用户
     */
    @PutMapping("/users/{userId}/ban")
    public Result banUser(@PathVariable Long userId) {
        boolean success = userService.updateUserStatus(userId, 1); // 1表示禁言状态
        if (success) {
            return Result.success("用户禁言成功");
        } else {
            return Result.error(ResultCode.OPERATION_FAILED, "用户禁言失败");
        }
    }

    /**
     * 解禁用户
     */
    @PutMapping("/users/{userId}/unban")
    public Result unbanUser(@PathVariable Long userId) {
        boolean success = userService.updateUserStatus(userId, 0); // 0表示正常状态
        if (success) {
            return Result.success("用户解禁成功");
        } else {
            return Result.error(ResultCode.OPERATION_FAILED, "用户解禁失败");
        }
    }

    /**
     * 添加用户
     */
    @PostMapping("/users")
    public Result addUser(@RequestBody User user) {
        try {
            // 验证必填字段
            if (user.getUsername() == null || user.getUsername().isEmpty() ||
                user.getPassword() == null || user.getPassword().isEmpty()) {
                return Result.error(ResultCode.PARAM_ERROR, "用户名和密码不能为空");
            }
            
            // 检查用户名是否已存在
            User existingUser = userService.getUserByUsername(user.getUsername());
            if (existingUser != null) {
                return Result.error(ResultCode.USER_ALREADY_EXIST, "用户名已存在");
            }
            
            // 设置默认值
            if (user.getRole() == null) {
                user.setRole(0); // 默认普通用户
            }
            if (user.getStatus() == null) {
                user.setStatus(0); // 默认正常状态
            }
            if (user.getCoinBalance() == null) {
                user.setCoinBalance(0); // 默认金币余额
            }
            
            // 添加用户
            User savedUser = userService.addUser(user);
            if (savedUser != null) {
                return Result.success("用户添加成功", savedUser);
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "用户添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "添加用户过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 编辑用户
     */
    @PutMapping("/users/{userId}")
    public Result updateUser(@PathVariable Long userId, @RequestBody User user) {
        System.out.println("开始编辑用户，用户ID: " + userId);
        System.out.println("接收到的用户信息: " + user);
        try {
            // 检查用户是否存在
            User existingUser = userService.findById(userId);
            System.out.println("查询到的用户信息: " + existingUser);
            if (existingUser == null) {
                System.out.println("用户不存在，用户ID: " + userId);
                return Result.error(ResultCode.NOT_FOUND, "用户不存在");
            }
            
            // 检查是否是管理员用户
            if (existingUser.getRole() == 1) {
                System.out.println("管理员用户不能编辑，用户ID: " + userId);
                return Result.error(ResultCode.FORBIDDEN, "管理员用户不能编辑");
            }
            
            // 只更新非空字段
            if (user.getNickname() != null) {
                System.out.println("更新昵称: " + user.getNickname());
                existingUser.setNickname(user.getNickname());
            }
            if (user.getPhone() != null) {
                System.out.println("更新手机号: " + user.getPhone());
                existingUser.setPhone(user.getPhone());
            }
            if (user.getEmail() != null) {
                System.out.println("更新邮箱: " + user.getEmail());
                existingUser.setEmail(user.getEmail());
            }
            if (user.getAvatar() != null) {
                System.out.println("更新头像: " + user.getAvatar());
                existingUser.setAvatar(user.getAvatar());
            }
            if (user.getIntroduction() != null) {
                System.out.println("更新简介: " + user.getIntroduction());
                existingUser.setIntroduction(user.getIntroduction());
            }
            if (user.getStatus() != null) {
                System.out.println("更新状态: " + user.getStatus());
                existingUser.setStatus(user.getStatus());
            }
            
            // 更新用户
            System.out.println("准备更新用户信息: " + existingUser);
            boolean success = userService.update(existingUser);
            System.out.println("用户更新结果: " + success);
            if (success) {
                return Result.success("用户编辑成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "用户编辑失败");
            }
        } catch (Exception e) {
            System.err.println("编辑用户过程中发生异常: ");
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "编辑用户过程中发生错误：" + e.getMessage());
        }
    }
    

    
    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    public Result deleteUser(@PathVariable Long userId) {
        // 检查是否是管理员用户
        User user = userService.findById(userId);
        if (user != null && user.getRole() == 1) {
            return Result.error(ResultCode.FORBIDDEN, "管理员用户不能删除");
        }
        
        boolean success = userService.deleteUser(userId);
        if (success) {
            return Result.success("用户删除成功");
        } else {
            return Result.error(ResultCode.OPERATION_FAILED, "用户删除失败");
        }
    }
    /**
     * 获取最近活动
     */
    @GetMapping("/activities/recent")
    public Result getRecentActivities() {
        // 这里应该从活动日志表中获取最近的活动记录
        // 由于暂时没有活动日志表，返回模拟数据
        List<Map<String, Object>> mockActivities = getMockRecentActivities();
        return Result.success("activities", mockActivities);
    }

    // 模拟最近活动数据
    private List<Map<String, Object>> getMockRecentActivities() {
        List<Map<String, Object>> activities = new java.util.ArrayList<>();
        
        Map<String, Object> activity1 = new HashMap<>();
        activity1.put("id", 1);
        activity1.put("username", "user123");
        activity1.put("type", "提问");
        activity1.put("time", new java.util.Date().toString());
        activity1.put("detail", "提出了问题 '如何提高编程效率?'");
        activities.add(activity1);
        
        Map<String, Object> activity2 = new HashMap<>();
        activity2.put("id", 2);
        activity2.put("username", "user456");
        activity2.put("type", "回答");
        activity2.put("time", new java.util.Date(System.currentTimeMillis() - 3600000).toString());
        activity2.put("detail", "回答了问题 '如何提高编程效率?'");
        activities.add(activity2);
        
        Map<String, Object> activity3 = new HashMap<>();
        activity3.put("id", 3);
        activity3.put("username", "user789");
        activity3.put("type", "充值");
        activity3.put("time", new java.util.Date(System.currentTimeMillis() - 7200000).toString());
        activity3.put("detail", "充值了100个金币");
        activities.add(activity3);
        
        return activities;
    }

    /**
     * 获取问题详情
     */
    @GetMapping("/questions/{questionId}")
    public Result getQuestionDetail(@PathVariable Long questionId) {
        try {
            // 获取问题详情
            Question question = questionService.findById(questionId);
            if (question == null) {
                return Result.error(ResultCode.NOT_FOUND, "问题不存在");
            }
            
            // 封装问题详情数据
            Map<String, Object> data = new HashMap<>();
            data.put("id", question.getId());
            data.put("title", question.getTitle());
            data.put("content", question.getContent());
            data.put("status", question.getStatus());
            data.put("reward", question.getRewardAmount());
            data.put("createTime", question.getCreateTime());
            data.put("userId", question.getUserId());
            
            // 获取提问者信息
            User user = userService.findById(question.getUserId());
            if (user != null) {
                data.put("username", user.getUsername());
                data.put("nickname", user.getNickname());
            } else {
                data.put("username", "未知用户");
                data.put("nickname", "未知用户");
            }
            
            // 获取该问题的回答列表
            List<Answer> answers = answerService.findByQuestionId(questionId);
            List<Map<String, Object>> answerList = new ArrayList<>();
            for (Answer answer : answers) {
                Map<String, Object> answerData = new HashMap<>();
                answerData.put("id", answer.getId());
                answerData.put("content", answer.getContent());
                answerData.put("status", answer.getStatus());
                answerData.put("accepted", answer.getIsAccepted());
                answerData.put("createTime", answer.getCreateTime());
                answerData.put("userId", answer.getUserId());
                
                // 获取回答者信息
                User answerUser = userService.findById(answer.getUserId());
                if (answerUser != null) {
                    answerData.put("username", answerUser.getUsername());
                    answerData.put("nickname", answerUser.getNickname());
                } else {
                    answerData.put("username", "未知用户");
                    answerData.put("nickname", "未知用户");
                }
                
                answerList.add(answerData);
            }
            
            data.put("answers", answerList);
            
            return Result.success("获取问题详情成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "获取问题详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 编辑问题
     */
    @PutMapping("/questions/{questionId}")
    public Result updateQuestion(@PathVariable Long questionId, @RequestBody Question question) {
        try {
            // 检查问题是否存在
            Question existingQuestion = questionService.findById(questionId);
            if (existingQuestion == null) {
                return Result.error(ResultCode.NOT_FOUND, "问题不存在");
            }
            
            // 设置问题ID（防止被修改）
            question.setId(questionId);
            
            // 更新问题
            boolean success = questionService.update(question);
            if (success) {
                return Result.success("问题编辑成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "问题编辑失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "编辑问题过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 关闭问题
     */
    @PutMapping("/questions/{questionId}/close")
    public Result closeQuestion(@PathVariable Long questionId) {
        try {
            // 检查问题是否存在
            Question question = questionService.findById(questionId);
            if (question == null) {
                return Result.error(ResultCode.NOT_FOUND, "问题不存在");
            }
            
            // 关闭问题
            boolean success = questionService.closeQuestion(questionId);
            if (success) {
                return Result.success("问题关闭成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "问题关闭失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "关闭问题过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 开启问题
     */
    @PutMapping("/questions/{questionId}/open")
    public Result openQuestion(@PathVariable Long questionId) {
        try {
            // 检查问题是否存在
            Question question = questionService.findById(questionId);
            if (question == null) {
                return Result.error(ResultCode.NOT_FOUND, "问题不存在");
            }
            
            // 开启问题
            question.setStatus(0); // 0表示开启状态
            boolean success = questionService.update(question);
            if (success) {
                return Result.success("问题开启成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "问题开启失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "开启问题过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 删除问题
     */
    @DeleteMapping("/questions/{questionId}")
    public Result deleteQuestion(@PathVariable Long questionId) {
        try {
            // 检查问题是否存在
            Question question = questionService.findById(questionId);
            if (question == null) {
                return Result.error(ResultCode.NOT_FOUND, "问题不存在");
            }
            
            // 删除问题
            boolean success = questionService.deleteById(questionId);
            if (success) {
                return Result.success("问题删除成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "问题删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "删除问题过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 获取问题列表
     */
    @GetMapping("/questions")
    public Result getQuestionList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status) {
        try {
            // 处理状态参数
            Integer statusValue = null;
            if (status != null && !status.isEmpty() && !"all".equals(status)) {
                statusValue = Integer.parseInt(status);
            }
            
            // 准备查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("start", (page - 1) * pageSize);
            params.put("pageSize", pageSize);
            params.put("keyword", keyword);
            params.put("status", statusValue);
            
            // 调用服务层方法获取分页数据
            List<?> questions = questionService.findPage(params);
            int total = questionService.findCount(params);
            
            Map<String, Object> data = new HashMap<>();
            data.put("questions", questions);
            data.put("total", total);
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "获取问题列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取回答详情
     */
    @GetMapping("/answers/{answerId}")
    public Result getAnswerDetail(@PathVariable Long answerId) {
        try {
            // 获取回答详情
            Answer answer = answerService.findById(answerId);
            if (answer == null) {
                return Result.error(ResultCode.NOT_FOUND, "回答不存在");
            }
            
            // 封装回答详情数据
            Map<String, Object> data = new HashMap<>();
            data.put("id", answer.getId());
            data.put("content", answer.getContent());
            data.put("status", answer.getStatus());
            data.put("accepted", answer.getIsAccepted());
            data.put("createTime", answer.getCreateTime());
            data.put("userId", answer.getUserId());
            data.put("questionId", answer.getQuestionId());
            
            // 获取回答者信息
            User user = userService.findById(answer.getUserId());
            if (user != null) {
                data.put("username", user.getUsername());
                data.put("nickname", user.getNickname());
            } else {
                data.put("username", "未知用户");
                data.put("nickname", "未知用户");
            }
            
            // 获取问题信息
            Question question = questionService.findById(answer.getQuestionId());
            if (question != null) {
                data.put("questionTitle", question.getTitle());
                data.put("questionReward", question.getRewardAmount());
                
                // 获取提问者信息
                User questionUser = userService.findById(question.getUserId());
                if (questionUser != null) {
                    data.put("questionUsername", questionUser.getUsername());
                } else {
                    data.put("questionUsername", "未知用户");
                }
            } else {
                data.put("questionTitle", "未知问题");
                data.put("questionReward", 0);
                data.put("questionUsername", "未知用户");
            }
            
            return Result.success("获取回答详情成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "获取回答详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 编辑回答
     */
    @PutMapping("/answers/{answerId}")
    public Result updateAnswer(@PathVariable Long answerId, @RequestBody Answer answer) {
        try {
            // 检查回答是否存在
            Answer existingAnswer = answerService.findById(answerId);
            if (existingAnswer == null) {
                return Result.error(ResultCode.NOT_FOUND, "回答不存在");
            }
            
            // 设置回答ID（防止被修改）
            answer.setId(answerId);
            
            // 更新回答
            boolean success = answerService.update(answer);
            if (success) {
                return Result.success("回答编辑成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "回答编辑失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "编辑回答过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 删除回答
     */
    @DeleteMapping("/answers/{answerId}")
    public Result deleteAnswer(@PathVariable Long answerId) {
        try {
            // 检查回答是否存在
            Answer answer = answerService.findById(answerId);
            if (answer == null) {
                return Result.error(ResultCode.NOT_FOUND, "回答不存在");
            }
            
            // 删除回答
            boolean success = answerService.deleteById(answerId);
            if (success) {
                return Result.success("回答删除成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "回答删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "删除回答过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 恢复回答
     */
    @PutMapping("/answers/{answerId}/restore")
    public Result restoreAnswer(@PathVariable Long answerId) {
        try {
            // 检查回答是否存在
            Answer answer = answerService.findById(answerId);
            if (answer == null) {
                return Result.error(ResultCode.NOT_FOUND, "回答不存在");
            }
            
            // 恢复回答（通过更新状态实现）
            Answer updatedAnswer = new Answer();
            updatedAnswer.setId(answerId);
            updatedAnswer.setStatus(0); // 假设0表示正常状态
            boolean success = answerService.update(updatedAnswer);
            if (success) {
                return Result.success("回答恢复成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "回答恢复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "恢复回答过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 获取回答列表
     */
    @GetMapping("/answers")
    public Result getAnswerList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status) {
        try {
            // 处理状态参数
            Integer statusValue = null;
            if (status != null && !status.isEmpty() && !"all".equals(status)) {
                statusValue = Integer.parseInt(status);
            }
            
            // 调用服务层方法获取分页数据
            List<?> answers = answerService.findAll();
            
            // 根据关键词过滤
            if (keyword != null && !keyword.isEmpty()) {
                answers = answers.stream()
                        .filter(answer -> {
                            try {
                                Map<String, Object> answerMap = (Map<String, Object>) answer;
                                return (answerMap.get("content") != null && 
                                        answerMap.get("content").toString().contains(keyword)) ||
                                       (answerMap.get("questionTitle") != null && 
                                        answerMap.get("questionTitle").toString().contains(keyword));
                            } catch (Exception e) {
                                return false;
                            }
                        })
                        .collect(java.util.stream.Collectors.toList());
            }
            
            // 根据状态过滤
            if (statusValue != null) {
                final Integer finalStatusValue = statusValue;
                answers = answers.stream()
                        .filter(answer -> {
                            try {
                                Map<String, Object> answerMap = (Map<String, Object>) answer;
                                return finalStatusValue.equals(answerMap.get("status"));
                            } catch (Exception e) {
                                return false;
                            }
                        })
                        .collect(java.util.stream.Collectors.toList());
            }
            
            // 分页处理
            int total = answers.size();
            int start = (page - 1) * pageSize;
            int end = Math.min(start + pageSize, total);
            List<?> paginatedAnswers = start < end ? answers.subList(start, end) : new java.util.ArrayList<>();
            
            Map<String, Object> data = new HashMap<>();
            data.put("answers", paginatedAnswers);
            data.put("total", total);
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "获取回答列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取金币交易记录
     */
    @GetMapping("/transactions")
    public Result getTransactionList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String type) {
        try {
            // 获取所有交易记录
            List<CoinTransaction> transactions = coinTransactionService.findAll();
            
            // 根据用户名过滤
            if (username != null && !username.isEmpty()) {
                transactions = transactions.stream()
                        .filter(transaction -> {
                            try {
                                // 通过用户ID获取用户名进行匹配
                                Long userId = transaction.getUserId();
                                User user = userService.findById(userId);
                                return user != null && user.getUsername().contains(username);
                            } catch (Exception e) {
                                e.printStackTrace();
                                return false;
                            }
                        })
                        .collect(java.util.stream.Collectors.toList());
            }
            
            // 根据交易类型过滤
            if (type != null && !type.isEmpty() && !"all".equals(type)) {
                Integer typeValue = null;
                switch (type) {
                    case "recharge":
                        typeValue = 0;
                        break;
                    case "question":
                        typeValue = 1;
                        break;
                    case "reward":
                        typeValue = 2;
                        break;
                    case "other":
                        typeValue = 3;
                        break;
                }
                
                if (typeValue != null) {
                    final Integer finalTypeValue = typeValue;
                    transactions = transactions.stream()
                            .filter(transaction -> transaction.getType() == finalTypeValue)
                            .collect(java.util.stream.Collectors.toList());
                }
            }
            
            // 分页处理
            int total = transactions.size();
            int start = (page - 1) * pageSize;
            int end = Math.min(start + pageSize, total);
            List<CoinTransaction> paginatedTransactions = start < end ? transactions.subList(start, end) : new java.util.ArrayList<>();
            
            // 为每个交易记录添加用户名和余额信息
            List<Map<String, Object>> enhancedTransactions = new java.util.ArrayList<>();
            for (CoinTransaction transaction : paginatedTransactions) {
                try {
                    Long userId = transaction.getUserId();
                    User user = userService.findById(userId);
                    
                    // 将CoinTransaction对象转换为Map
                    Map<String, Object> enhancedTransaction = new HashMap<>();
                    enhancedTransaction.put("id", transaction.getId());
                    enhancedTransaction.put("userId", transaction.getUserId());
                    enhancedTransaction.put("amount", transaction.getAmount());
                    enhancedTransaction.put("type", transaction.getType());
                    enhancedTransaction.put("remark", transaction.getRemark());
                    enhancedTransaction.put("createTime", transaction.getCreateTime());
                    
                    // 添加用户名和余额信息
                    if (user != null) {
                        enhancedTransaction.put("username", user.getUsername());
                        enhancedTransaction.put("balanceAfter", user.getCoinBalance());
                    } else {
                        enhancedTransaction.put("username", "未知用户");
                        enhancedTransaction.put("balanceAfter", 0);
                    }
                    
                    enhancedTransactions.add(enhancedTransaction);
                } catch (Exception e) {
                    e.printStackTrace();
                    // 处理单个交易记录的异常，继续处理下一个
                    continue;
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("transactions", enhancedTransactions);
            data.put("total", total);
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return new Result<>(ResultCode.SUCCESS.getCode(), "获取成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "获取交易记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置管理员密码
     * 注意：此接口仅用于开发和测试环境，生产环境应移除或增加更严格的安全验证
     */
    @PutMapping("/admin/reset-password")
    public Result resetAdminPassword() {
        try {
            boolean success = userService.resetAdminPassword();
            if (success) {
                return Result.success("管理员密码重置成功，新密码为：admin123");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "管理员密码重置失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "重置管理员密码过程中发生错误：" + e.getMessage());
        }
    }
    
    /**
     * 安全的管理员注册接口
     * 注意：此接口只允许已登录的管理员创建新的管理员账号
     */
    @PostMapping("/admin/register")
    public Result registerAdmin(@RequestBody Map<String, String> adminInfo, HttpServletRequest request) {
        try {
            // 1. 验证请求者是否为已登录的管理员
            // 在实际应用中，应该从session或token中获取当前登录的管理员信息
            // 这里假设已登录的管理员信息在request中
            // 注意：这只是一个示例，实际应该实现完整的身份验证机制
            User currentAdmin = (User) request.getAttribute("currentAdmin");
            if (currentAdmin == null || currentAdmin.getRole() != 1) {
                return Result.error(ResultCode.FORBIDDEN, "只有管理员才能创建新的管理员账号");
            }
            
            // 2. 验证必填参数
            String username = adminInfo.get("username");
            String password = adminInfo.get("password");
            String confirmPassword = adminInfo.get("confirmPassword");
            String email = adminInfo.get("email");
            String phone = adminInfo.get("phone");
            
            if (username == null || username.trim().isEmpty()) {
                return Result.error(ResultCode.PARAM_ERROR, "用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error(ResultCode.PARAM_ERROR, "密码不能为空");
            }
            if (confirmPassword == null || !confirmPassword.equals(password)) {
                return Result.error(ResultCode.PARAM_ERROR, "两次输入的密码不一致");
            }
            if (email == null || email.trim().isEmpty()) {
                return Result.error(ResultCode.PARAM_ERROR, "邮箱不能为空");
            }
            if (phone == null || phone.trim().isEmpty()) {
                return Result.error(ResultCode.PARAM_ERROR, "手机号不能为空");
            }
            
            // 3. 验证邮箱和手机号格式
            if (!email.matches("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$")) {
                return Result.error(ResultCode.PARAM_ERROR, "邮箱格式不正确");
            }
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                return Result.error(ResultCode.PARAM_ERROR, "手机号格式不正确");
            }
            
            // 4. 检查用户名、手机号、邮箱是否已存在
            if (userService.getUserByUsername(username) != null) {
                return Result.error(ResultCode.USER_ALREADY_EXIST, "用户名已存在");
            }
            
            // 使用UserMapper直接检查手机号和邮箱是否存在
            if (userMapper.selectByPhone(phone) != null) {
                return Result.error(ResultCode.PARAM_ERROR, "手机号已被使用");
            }
            
            if (userMapper.selectByEmail(email) != null) {
                return Result.error(ResultCode.PARAM_ERROR, "邮箱已被使用");
            }
            
            // 5. 创建管理员用户
            User newAdmin = new User();
            newAdmin.setUsername(username);
            newAdmin.setPassword(password); // 密码会在service层加密
            newAdmin.setEmail(email);
            newAdmin.setPhone(phone);
            newAdmin.setRole(1); // 设置为管理员角色
            newAdmin.setStatus(0); // 设置为正常状态
            newAdmin.setCoinBalance(0); // 初始金币余额为0
            newAdmin.setCreateTime(new Date());
            newAdmin.setUpdateTime(new Date());
            
            // 6. 保存管理员用户
            User savedAdmin = userService.addUser(newAdmin);
            if (savedAdmin != null) {
                // 7. 记录操作日志（实际应用中应实现完整的日志系统）
                System.out.println("管理员 " + currentAdmin.getUsername() + " 创建了新管理员 " + username);
                
                return Result.success("管理员账号创建成功");
            } else {
                return Result.error(ResultCode.OPERATION_FAILED, "管理员账号创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.OPERATION_FAILED, "创建管理员账号过程中发生错误：" + e.getMessage());
        }
    }
}